package com.zh.juc.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: zhanghuan
 * @date: 2022/10/9 19:55
 * @description: create it
 * <p>
 * 公平锁与非公平锁
 * ReentrantLock默认就是非公平锁
 * ReentrantLock(true) 公平锁
 * <p>
 * 面试题：为什么默认是非公平锁？
 * 非公平锁更能充分利用cpu时间片，减少cpu空闲时间
 * 线程切换使用cpu的过程，开销特别大
 * <p>
 *
 */

// 资源类，模拟3个售票员，卖完50张票
class Ticket {
    private int number = 50;
    Lock lock = new ReentrantLock(true);

    public void sale() {
        lock.lock();
        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "\t" + (number--) + "\t 还剩下" + number + "张票");
            }
        } finally {
            lock.unlock();
        }

    }
}

public class SaleTicketDemo {

    public static void main(String[] args) {
        Ticket ticket = new Ticket();

        new Thread(() -> {
            for (int i = 0; i < 55; i++) ticket.sale();
        }, "a").start();
        new Thread(() -> {
            for (int i = 0; i < 55; i++) ticket.sale();
        }, "b").start();
        new Thread(() -> {
            for (int i = 0; i < 55; i++) ticket.sale();
        }, "c").start();
    }
}
